<template>
    <div>
         <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 添加商品按钮区域 -->
            <el-row>
                <el-col>
                    <el-button type="primary">添加商品</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表区域 -->
            <el-table row-key="key" :data="roleList" border stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                       <el-row v-for="(item1, i1) in scope.row.children" :key="item1.key" :class="['border_bot', i1===0?'border_top':'', 'vcenter']">
                           <!-- 渲染一级权限 -->
                           <el-col :span="5">
                               <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                               <i class="el-icon-caret-right"></i>
                           </el-col>
                           <!-- 渲染二级和三级权限 -->
                           <el-col :span="19">
                               <el-row :class="[i2 === 0? '': 'border_top', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.key">
                                   <!-- 渲染二级权限 -->
                                   <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                   </el-col>
                                    <!-- 渲染三级权限 -->
                                   <el-col :span="18">
                                       <el-tag v-for="(item3) in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                                   </el-col>
                               </el-row>
                           </el-col>
                       </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting" @click="showRightsDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 权限管理对话框 -->
            <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" @close="setRightsClose">
                <!-- 权限管理的树形结构 -->
                <el-tree :data="rightsList" :props="rightsProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="checKeys"
                ref="treeRef"></el-tree>
                <span slot="footer">
                    <el-button @click="setRightsDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="setRights">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
//定义函数生成MD5
function randomString(len) {
　　len = len || 32;
 　var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  　　var maxPos = $chars.length;
  　　var pwd = '';
  　　for (var i = 0; i < len; i++) {
  　　　　pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  　　}
 　　return pwd;
 }

 function getKey(arr){
   arr.forEach(item => {
     item.key = randomString()
     if(!item.children) return
     getKey(item.children)
   })
 }

export default {
  data() {
    return {
      // 角色列表信息
      roleList: [],
      // 控制分配权限是否显示
      setRightsDialogVisible: false,
      // 权限列表信息
      rightsList: [],
      // 权限管理的树形结构绑定的属性
      rightsProps: {
        label: 'authName',
        children: 'children'
      },
      // 权限管理的树形结构默认勾选的节点的 key 的数组
      checKeys: [],
      // 当前角色的id
      roleId: ''
    }
  },
  created() {
    // 初始化时获取角色列表
    this.getRoleList()
  },
  methods: {
    // 获取所有角色列表信息
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      // 循环返回值 给每一个对象加一个新的属性 rid 值就是md5
      getKey(res.data)
      if (res.meta.status !== 200) return this.$message.error('获取信息失败！')
      this.roleList = res.data
      console.log(this.roleList)
    },
    // 根据id删除用户权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除!')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败!')
      role.children = res.data
      this.$message.success('删除成功!')
    },
    // 显示分配权限对话框
    async showRightsDialog(role) {
      this.roleId = role.id
      // 获取权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.err('获取权限列表数据失败！')
      this.rightsList = res.data
      // console.log(this.rightsList);
      // 获取权限管理树形结构的默认勾选
      this.getLeafKeys(role, this.checKeys)
      // 显示分配权限对话框
      this.setRightsDialogVisible = true
    },
    // 获取权限管理的树形结构默认勾选的节点的 key 的数组
    getLeafKeys(node, arr) {
      if (!node.childNodes) {
        return arr.push(node)
      }
      node.childNodes.foreach(item => {
        this.getLeafKeys(item)
      })
    },
    // 点击关闭权限管理对话框
    setRightsClose() {
      this.checKeys = []
    },
    // 设置权限
    async setRights() {
      // console.log(this.$ref);
      var rids = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]
      var ridsStr = rids.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: ridsStr
      })
      if (res.meta.status !== 200) {
        return this.$http.error('设置权限失败！')
      }

      this.$http.success('设置权限成功！')
      this.setRightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
    .el-tag{
        margin: 7px;
    }
    .border_top{
        border-top: 1px solid #eee;
    }
    .border_bot{
        border-bottom: 1px solid #eee;
    }
    .vcenter{
        display: flex;
        align-items: center;
    }
</style>
